<?php
namespace pay;
use  think\Request;
use   think\Config;
date_default_timezone_set('PRC');
header("Content-Type:application/json; charset=UTF-8");
class Tixia{

    private  $apiKey;
    private  $callback;
    private  $notify_url;
    public function __construct()
    {
            $class = strtolower("Tixia");

            $this->Config  = $Config = Config::get($class);
            $this->apiKey = $Config['apiKey'];
            $this->mchId = $Config['mchId'];
            $this->URL = $Config['URL'];

            $domain = Request::instance()->domain();
            //curl实例
            $this->http =new \http\Http();
        if(!empty($Config['callback_url'])){
            $this->callback = $Config['callback_url'];
        }else{
            $this->callback = $domain."/out/Notify/callbackurl";
        }
        if(!empty($Config['notify_url'])){
            $this->notify_url = $Config['notify_url'];
        }else{
            $this->notify_url =$domain."/out/Notify/handtx";
        }
    }


    /**
     *  网关支付
     */
    public function byPay($deposit,$payNo,$CertName,$CertNo,$Phone){
        $baseData = $this->baseData();
        $payData = $this->payData($deposit,$CertNo,$payNo);

        $baseData['data'] = base64_encode(json_encode($payData));//64编码

       $signature =  $this->signature($baseData);
        $baseData['signature'] = $signature;//64编码

       $res = $this->http->sendRequest2($this->URL,$baseData,  'POST');


        if(!empty($res)){
                $result = json_decode($res,true);
                if($result['resultCode']!=200){
                         return ['status'=>0,"msg"=>$result['message']];
                }else{
                    if(isset($result['data'])){
                        $data = json_decode(base64_decode($result['data']),true);
                        return $data['url'];
                    }
                }
        }
        return false;


    }



    public function payData($deposit,$CertNo,$payNo){
  /*   $data = [
         "outOrderId"=>$payNo,
         "body"=>"天下金慧支付",
         "name"=>"天下金慧支付",
         "amount"=>bcmul($deposit,100),
         "bankCode"=>"ICBC",
         "frontUrl"=>$this->callback,
         "notifyUrl"=>$this->notify_url,
     ];*/
/*
        outOrderId String(32) 是 商户订单号
subject String 是 订单描述
frontUrl String 是 前台地址
amount Long 是 订单金额，以分为单位，
不允许包含任何字、符号
notifyUrl String 是 后台异步通知 url*/

  $data = [
         "outOrderId"=>$payNo,
         "subject"=>"天下金慧支付",
         "amount"=>bcmul($deposit,100),
         "frontUrl"=>$this->callback,
         "notifyUrl"=>$this->notify_url,
     ];
     return $data;
    }


    public function Notify($result){
        $files = "/home/wwwlogs/controller_Notify_tixia.log";
        $tdata = ["msg"=>"异常","status"=>0,"data"=>[]];
        $arr = ["notifyId","notifyTime","notifyType","orderId","outOrderId","buyerId","orderStatus","amount","payTime","attach","charset"];
        //$arr = ksort($arr);signature
        $result = json_decode($result,true);
        if($result['orderStatus']!="SUCCESS"){ //充值成功

            // 回滚事务
            if(getOS()=="Linux"){
                error_log("订单号".$result['outOrderId']."已被银行折返",3,$files);
            }
            return array_merge($tdata,['status'=>0,"msg"=>"改订单已被银行折返"]);
        }

        $darr = [];
        foreach ($result as $k=>$v){
                if(!empty($v)&&in_array($k,$arr)){
                    $darr[$k] = $v;
                }
        }
        ksort($darr);//字典排序
        $signature = $this->signature($darr);
        if($signature !=$result['signature'] ){//
            if(getOS()=="Linux"){
                error_log("订单号".$result['outOrderId']."签名失败",3,$files);
            }
            return array_merge($tdata,["msg"=>"签名失败"]);
        }
        $NotifySignModel  = new \app\admin\model\UsersRecharge();
        $res = $NotifySignModel->where("thirdparty_payno",$result['outOrderId'])->find();
        if($res['status']==2){
            if(getOS()=="Linux"){
                error_log("订单号".$result['outOrderId']."已失效",3,$files);
            }
            return array_merge($tdata,['status'=>0,"msg"=>"该订单已失效"]);
        }
        if($res['status']==1){
            if(getOS()=="Linux"){
                error_log("订单号".$result['outOrderId']."已充值成功",3,$files);
            }
            return array_merge($tdata,['status'=>0,"msg"=>"该订单已充值成功"]);
        }

        $resultBa['app_id'] =$res['thirdparty_payno'];
        $resultBa['amount'] =$result['amount'];

        return  ["data"=>$resultBa,"status"=>1,"msg"=>"验证成功"];


    }








    /**
     *   生成签名
     */
    public function signature($data){
        ksort($data);//字典排序
        $dataString = "";
        foreach($data as $k=>$v){
            $dataString .=$k."=".$v."&";
        }
        $stringSignTemp =  $dataString."key=".$this->apiKey;
        $md5String = strtoupper(md5($stringSignTemp));
        return $md5String;
    }




    /**
     * @return array 获取那个基本参数
     */
    private function baseData(){
       $data = [
           "mchId"=>$this->mchId,
           "timestamp"=>date("YmdHis")."000",
           "data"=>"",
       ];
        return $data;
    }





}
?>
